<?php


namespace App\Console\Commands;


use Aitels\Foundation\Annotation\ApplicationAnnotationsContainer;
use Aitels\Foundation\Annotation\RouteAnnotation;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Modules\Common\Models\AdminPermission;
use Modules\Common\Util\Database;

class UpdatePermission extends Command
{
    protected $signature = 'permission:update';
    protected $description = '缓存注解';

    public function handle()
    {
        $routeAnnotations = ApplicationAnnotationsContainer::getApplicationAnnotations(RouteAnnotation::NAME);
        foreach ($routeAnnotations as $classPath => $methodsAnnotations) {
            foreach ($methodsAnnotations as $methodName => $methodAnnotations) {
                foreach ($methodAnnotations as $routeAnnotation) {
                    $path = $routeAnnotation['path'];
                    $path = Str::startsWith($path, '/') ? $path : '/' . $path;
                    $method = strtoupper($routeAnnotation['method'] ?? 'get');
                    $name = Str::random(5);
                    if (Str::is('*api/admin/*', $path) &&
                        !Str::is('*api/admin/authorization/*', $path)) {
                        if (AdminPermission::wherePath($path)->whereMethod($method)->doesntExist()) {
                            $p = new AdminPermission();
                            $p->name = $name;
                            $p->path = $path;
                            $p->method = $method;
                            $p->disable = Database::BOOL_FALSE;
                            $p->save();
                        }
                    }
                }
            }
        }
    }

}
